-- Lua Battle System - 随机数生成工具

local Random = {}

-- 初始化随机种子
function Random:init(seed)
    if seed then
        math.randomseed(seed)
    else
        math.randomseed(os.time())
    end
    -- 预热随机数生成器
    for i = 1, 10 do
        math.random()
    end
end

-- 生成整数随机数 [min, max]
function Random:int(min, max)
    if not min then
        min = 0
        max = 1
    elseif not max then
        max = min
        min = 0
    end
    return math.random(min, max)
end

-- 生成浮点数随机数 [min, max)
function Random:float(min, max)
    if not min then
        min = 0
        max = 1
    elseif not max then
        max = min
        min = 0
    end
    return min + (max - min) * math.random()
end

-- 生成布尔值随机数
function Random:bool(probability)
    probability = probability or 0.5
    return self:float() < probability
end

-- 从列表中随机选择一个元素
function Random:choice(list)
    if not list or #list == 0 then
        return nil
    end
    local index = self:int(1, #list)
    return list[index]
end

-- 从列表中随机选择多个元素（不重复）
function Random:sample(list, count)
    if not list or #list == 0 then
        return {}
    end
    
    count = count or 1
    local result = {}
    local temp_list = {}
    
    -- 复制列表
    for i, value in ipairs(list) do
        temp_list[i] = value
    end
    
    -- 随机选择
    for i = 1, math.min(count, #temp_list) do
        local index = self:int(1, #temp_list)
        table.insert(result, temp_list[index])
        table.remove(temp_list, index)
    end
    
    return result
end

-- 打乱列表
function Random:shuffle(list)
    if not list or #list == 0 then
        return list
    end
    
    local result = {}
    for i, value in ipairs(list) do
        result[i] = value
    end
    
    for i = #result, 2, -1 do
        local j = self:int(1, i)
        result[i], result[j] = result[j], result[i]
    end
    
    return result
end

-- 按权重随机选择
function Random:weighted_choice(weighted_list)
    if not weighted_list or #weighted_list == 0 then
        return nil
    end
    
    local total_weight = 0
    for _, item in ipairs(weighted_list) do
        total_weight = total_weight + (item.weight or 1)
    end
    
    local random_value = self:float(0, total_weight)
    local current_weight = 0
    
    for _, item in ipairs(weighted_list) do
        current_weight = current_weight + (item.weight or 1)
        if random_value < current_weight then
            return item.value
        end
    end
    
    return nil
end

-- 导出模块
return Random